package com.xmut.bs.handaccount.fragment;


import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.xmut.bs.handaccount.GlideApp;
import com.xmut.bs.handaccount.R;
import com.xmut.bs.handaccount.base.BaseFragment;
import com.xmut.bs.handaccount.bmob.Comment;
import com.xmut.bs.handaccount.bmob.Order;
import com.xmut.bs.handaccount.bmob.User;
import com.xmut.bs.handaccount.util.DividerItemDecoration;
import com.xmut.bs.handaccount.util.StringUtil;
import com.xmut.bs.handaccount.widget.TagTextView;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

import static com.xmut.bs.handaccount.base.Constants.ORDER_COMMENT;
import static com.xmut.bs.handaccount.base.Constants.ORDER_COMPLETE;
import static com.xmut.bs.handaccount.base.Constants.ORDER_RECEIPT;
import static com.xmut.bs.handaccount.base.Constants.ORDER_WAIT;
import static com.xmut.bs.handaccount.base.Constants.PARAM_ORDER_MANAGER;


/**
 * A simple {@link Fragment} subclass.
 */
public class OrderFragment extends BaseFragment implements BGARefreshLayout.BGARefreshLayoutDelegate {

    private static final String ARG_SECTION_NUMBER = "section_number";
    @BindView(R.id.nearby_person_rv)
    RecyclerView mNearbyPersonRv;
    @BindView(R.id.refresh_layout)
    BGARefreshLayout mRefreshLayout;

    private int status;
    private List<Order> mOrderList;
    private int pageNo = 1;
    private int pageSize = 20;
    private RecyclerView.Adapter mAdapter;
    private BmobQuery<Order> mBmobQuery;
    private User mUser;
    private boolean isManager;


    public static OrderFragment newInstance(int sectionNumber, boolean isManager) {
        OrderFragment fragment = new OrderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        args.putBoolean(PARAM_ORDER_MANAGER, isManager);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_nearby_person;
    }

    @Override
    protected void init() {
        status = getArguments().getInt(ARG_SECTION_NUMBER);
        isManager = getArguments().getBoolean(PARAM_ORDER_MANAGER);
        mOrderList = new ArrayList<>();
        mBmobQuery = new BmobQuery<>();
        mUser = BmobUser.getCurrentUser(User.class);
        mNearbyPersonRv.setLayoutManager(new LinearLayoutManager(mContext));
        mNearbyPersonRv.setItemAnimator(new DefaultItemAnimator());
        mNearbyPersonRv.addItemDecoration(new DividerItemDecoration(mContext));

        initRefreshLayout(mRefreshLayout, this);
    }

    @Override
    public void onResume() {
        super.onResume();
        mRefreshLayout.beginRefreshing();
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        mOrderList.clear();
        pageNo = 0;
        query();
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
        pageNo++;
        query();
        return false;
    }

    private void query() {
        mBmobQuery.setSkip(pageNo * pageSize);
        mBmobQuery.setLimit(pageSize);
        mBmobQuery.addWhereEqualTo("user", mUser);
        if (status > 0) {
            mBmobQuery.addWhereEqualTo("status", status);
        } else {
            mBmobQuery.addWhereNotEqualTo("status", status);
        }
        mBmobQuery.include("goods");
        mBmobQuery.findObjects(new FindListener<Order>() {
            @Override
            public void done(List<Order> list, BmobException e) {
                mRefreshLayout.endRefreshing();
                mRefreshLayout.endLoadingMore();
                if (e == null) {
                    if (list != null && list.size() > 0)
                        mOrderList.addAll(list);
                    setAdapter();
                } else {
                    showToast("失败：" + e.getMessage() + "," + e.getErrorCode());
                }
            }
        });
    }

    private void setAdapter() {
        if (mAdapter == null) {
            mAdapter = new EmptyWrapper<>(getAdapter());
            ((EmptyWrapper) mAdapter).setEmptyView(R.layout.common_empty);
            mNearbyPersonRv.setAdapter(mAdapter);
        } else {
            mAdapter.notifyDataSetChanged();
        }
    }

    @NonNull
    private CommonAdapter<Order> getAdapter() {
        return new CommonAdapter<Order>(mContext, R.layout.item_order, mOrderList) {
            @Override
            protected void convert(ViewHolder holder, final Order order, int position) {
                holder.getConvertView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                    }
                });
                ImageView goodImg = holder.getView(R.id.good_img_iv);
                GlideApp.with(goodImg)
                        .load(order.getGoods().getBannerUrls().get(0))
                        .fitCenter()
                        .placeholder(R.color.grey300)
                        .error(R.color.grey300)
                        .into(goodImg);
                holder.setText(R.id.title_tv, order.getGoods().getName());
                holder.setText(R.id.count_tv, String.valueOf(order.getCount()));
                holder.setText(R.id.pay_time_tv, order.getCreatedAt());
                TagTextView checkBtn = holder.getView(R.id.check_btn);
                switch (order.getStatus()) {
                    case ORDER_RECEIPT:
                        checkBtn.setTagText(isManager ? "待收货" : "确认收货");
                        checkBtn.setCheckBackgroundColor(mContext.getResources().getColor(isManager ? R.color.grey500 : R.color.orange300));
                        break;
                    case ORDER_COMMENT:
                        checkBtn.setTagText("去评价");
                        checkBtn.setCheckBackgroundColor(mContext.getResources().getColor(isManager ? R.color.grey500 : R.color.teal300));
                        break;
                    case ORDER_WAIT:
                        checkBtn.setTagText(isManager ? "确认发货" : "待发货");
                        checkBtn.setCheckBackgroundColor(mContext.getResources().getColor(isManager ? R.color.teal300 : R.color.grey500));
                        break;
                    case ORDER_COMPLETE:
                        checkBtn.setTagText("已完成");
                        checkBtn.setCheckBackgroundColor(mContext.getResources().getColor(R.color.grey500));
                        break;
                }
                checkBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isManager) {
                            if (order.getStatus() == ORDER_WAIT) {
                                order.setStatus(ORDER_RECEIPT);
                                order.update(new UpdateListener() {
                                    @Override
                                    public void done(BmobException e) {
                                        if (e == null) {
                                            showToast("确认发货成功");
                                            mRefreshLayout.beginRefreshing();
                                        } else {
                                            showToast("失败：" + e.getMessage() + "," + e.getErrorCode());
                                        }
                                    }
                                });
                            }
                        } else {
                            if (order.getStatus() == ORDER_RECEIPT) {
                                order.setStatus(ORDER_COMMENT);
                                order.update(new UpdateListener() {
                                    @Override
                                    public void done(BmobException e) {
                                        if (e == null) {
                                            showToast("确认收货成功");
                                            mRefreshLayout.beginRefreshing();
                                        } else {
                                            showToast("失败：" + e.getMessage() + "," + e.getErrorCode());
                                        }
                                    }
                                });
                            } else if (order.getStatus() == ORDER_COMMENT) {
                                final EditText et = new EditText(mContext);
                                new AlertDialog.Builder(mContext)
                                        .setTitle("请输入评价")
                                        .setView(et)
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                String trim = et.getText().toString().trim();
                                                if (StringUtil.isNull(trim)) {
                                                    showToast("评论内容不能为空");
                                                } else {
                                                    dialog.dismiss();
                                                    Comment comment = new Comment();
                                                    comment.setGoods(order.getGoods());
                                                    comment.setComment(trim);
                                                    comment.setUser(mUser);
                                                    comment.save(new SaveListener<String>() {
                                                        @Override
                                                        public void done(String s, BmobException e) {
                                                            if (e == null) {
                                                                showToast("评论成功");
                                                                mRefreshLayout.beginRefreshing();
                                                                order.setStatus(ORDER_COMPLETE);
                                                                order.update();
                                                            } else {
                                                                showToast("评论失败：" + e.getMessage() + "," + e.getErrorCode());
                                                            }
                                                        }
                                                    });
                                                }
                                            }
                                        })
                                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                            }
                                        })
                                        .show();
                            }
                        }
                    }
                });
            }
        };
    }
}
